package toledo.post;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;

import toledo.rest.Entry;
import toledo.rest.Update;
import toledo.rest.User;
 
public class AddEntryServlet extends HttpServlet
{
	private static final long serialVersionUID=1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	 {
		String course_id = req.getParameter(Entry.COURSE_ID);
		String user_id = req.getParameter(Entry.USER_ID);
		String text = req.getParameter(Entry.TEXT);
		String type = Entry.TYPE_POST;
		String reply_to_id = "";
		String date = new Date().toString();
		
		Entity e = new Entity(Entry.DATABASE);
		e.setProperty(Entry.COURSE_ID,course_id);
		e.setProperty(Entry.USER_ID,user_id);
		e.setProperty(Entry.TEXT,text);
		e.setProperty(Entry.DATE,date);
		e.setProperty(Entry.REPLY_TO_ID,reply_to_id);
		e.setProperty(Entry.TYPE,type);
		DatastoreServiceFactory.getDatastoreService().put(e);
		
		Entity update = new Entity("updates");
		update.setProperty(Update.COURSE_ID,course_id);
		update.setProperty(Update.USER_ID,user_id);
		update.setProperty(Update.ENTRY_ID,KeyFactory.keyToString(e.getKey()));
		update.setProperty(Update.TYPE,Update.TYPE_POST);
		DatastoreServiceFactory.getDatastoreService().put(update);
		 
		//resp.sendRedirect("database.jsp");
		JSONObject o = new JSONObject();
		Entity user = User.getUser(user_id);
		String key = KeyFactory.keyToString(e.getKey());
		try
		{
			o.put(Entry.ENTRY_ID,key);
			o.put(User.FULLNAME,user.getProperty(User.FULLNAME));
			o.put(User.PIC_URL,user.getProperty(User.PIC_URL));
			o.put(Entry.DATE,date);
			o.put(Entry.TYPE,type);
			o.put(Entry.TEXT,text);
			o.put(Entry.NUM_REPLIES,0);
		}
		catch(JSONException e1)
		{
			
		}
		PrintWriter writer =  resp.getWriter();
		writer.write(o.toString());
		writer.close();
	 }
}
